<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <!-- <el-form :inline="true" size="medium">
            <el-form-item>
              <el-button type="primary" @click="showAddDialogForm">新增</el-button>
            </el-form-item>
          </el-form> -->

          <el-form :inline="true" size="medium" :model="searchForm">

            <el-form-item label="姓名">
              <el-input v-model="searchForm.name" placeholder="姓名"></el-input>
            </el-form-item>

            <el-form-item label="部门" label-width="100px">
              <el-select v-model="searchForm.department" clearable  placeholder="请选择">
                <el-option
                  v-for="item in this.department"
                  :key="item.id"
                  :label="item.title"
                  :value="item.title">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="职位" label-width="100px">
              <el-select v-model="searchForm.position" clearable  placeholder="请选择">
                <el-option
                  v-for="item in this.position"
                  :key="item.id"
                  :label="item.position"
                  :value="item.position">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="选择时间" label-width="100px">
              <el-select v-model="searchForm.selectTimeId" clearable  placeholder="请选择">
                <el-option
                  v-for="item in selectTimeId"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label-width="100px">
              <el-date-picker
                v-model="searchForm.selectTime"
                type="datetimerange"
                align="right"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="打卡结果" label-width="100px">
              <el-select v-model="searchForm.punchResult" clearable  placeholder="请选择">
                <el-option
                  v-for="item in punchResult"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="clear">清空</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">

      <el-table-column
        align="center"
        prop="name"
        label="员工姓名"
        min-width="60">
      </el-table-column>
      <el-table-column
        align="center"
        prop="department"
        label="部门"
        min-width="60">
      </el-table-column>
      <el-table-column
        align="center"
        prop="workName"
        label="考勤组"
        min-width="60">
      </el-table-column>
      <el-table-column
        align="center"
        prop="position"
        label="职位"
        min-width="60">
      </el-table-column>
      <el-table-column
        align="center"
        prop=""
        label="考勤日期"
        min-width="60">
        <template scope="scope">
          {{fmtDate2(scope.row.time)}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop=""
        label="考勤时间"
        min-width="60">
        <template scope="scope">
          {{fmtDate3(scope.row.time,scope.row.beOnDutyTime,scope.row.offDutyTime)}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="time"
        label="打卡时间"
        min-width="60">
        <template scope="scope">
          {{fmtDate(scope.row.time)}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="recordState"
        label="打卡结果"
        min-width="60">
        <!-- <template scope="scope">
          {{fmtDate4(scope.row.time,scope.row.beOnDutyTime,scope.row.offDutyTime,scope.row.day)}}
        </template> -->
      </el-table-column>
      <el-table-column
        align="center"
        prop=""
        label="打卡备注"
        min-width="60">
      </el-table-column>
      <el-table-column
        align="center"
        prop="snName"
        label="设备名称"
        min-width="60">
      </el-table-column>
      <el-table-column
        align="center"
        prop="sn"
        label="设备sn"
        min-width="60">
      </el-table-column>


      <!-- <el-table-column
        align="center"
        prop="time"
        label="记录时间"
        min-width="60">
        <template scope="scope">
          {{fmtDate(scope.row.time)}}
        </template>
      </el-table-column> -->

      <el-table-column
        prop="photo"
        label="人脸图片"
        min-width="30">
        <template scope="scope">
          <el-image
            style="width: 90px; height: 120px"
            :src="scope.row.photo"
            :preview-src-list="[scope.row.photo]">
          </el-image>
        </template>

      </el-table-column>


      <!-- <el-table-column
        prop="address"
        label="操作"
        min-width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      <!-- </el-table-column> --> -->
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="编号" label-width="100px" prop="serialNumber">
          <el-input v-model="editForm.serialNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称" label-width="100px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" label-width="100px" prop="startTime">
          <el-input v-model="editForm.startTime" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="结束时间" label-width="100px" prop="endTime">
          <el-input v-model="editForm.endTime" autocomplete="off"></el-input>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getDepartmentList} from '@/api/go_department'
import {getGoPositionList} from "@/api/go_position.js";
import {getGoTimeFrameList, addGoTimeFrame, updateGoTimeFrame, deleteGoTimeFrame} from "@/api/go_time_frame";
import {getStaffLogsList,getUserStaffLogsList} from "@/api/go_staff_logs";

export default {
  name: "staffLogs",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      department:[],
      position:[],
      selectTimeId:[{
        value:'1',
        label:'考勤时间'
      },{
        value:'2',
        label:'打卡时间'
      }],
      punchResult:[{
        value:'重复打卡',
        label:'重复打卡'
      },{
        value:'下班打卡',
        label:'下班打卡'
      },{
        value:'迟到打卡',
        label:'迟到打卡'
      }],
      editForm: {
        id: 0,
        name: '',
        serialNumber: '',
        startTime:'',
        endTime:'',
      },
      editRules: {
        serialNumber: [{ required: true, message:"请输入编号", trigger: 'blur'}],
        name: [{ required: true, message:"请输入名称", trigger: 'blur'}],
      },
      loadingDiv: null,
      searchForm: {
        name:'',
        department:'',
        position:'',
        selectTime:'',
        selectTimeId:'',
        punchResult:'',
      },
      roleList:[],
    }
  },
  watch:{

  },
  mounted() {
    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }
  },
  methods: {
    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2*1000), fmt);
    },
    fmtDate2(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      var date = util.fmtDates(new Date(d2*1000), fmt);

      var dateString = date;
      var dateObject = new Date(dateString);

      // console.log(dateObject.getDate());
      var week;
      				if(dateObject.getDay()==0) week="周日"
      				if(dateObject.getDay()==1) week="周一"
      				if(dateObject.getDay()==2) week="周二"
      				if(dateObject.getDay()==3) week="周三"
      				if(dateObject.getDay()==4) week="周四"
      				if(dateObject.getDay()==5) week="周五"
      				if(dateObject.getDay()==6) week="周六"
      				return date+'  '+week;

    },

    fmtDate3(d2, beOnDutyTime,offDutyTime) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      var times = new Date(d2*1000);
      if(times.getHours()>=18){
        var t = new Date(offDutyTime);
      }else{
        var t = new Date(beOnDutyTime);
      }
      	var time =  this.format(t,'HH:mm:ss');
      return  util.fmtDates(new Date(d2*1000))+' '+time;
    },

    fmtDate4(d2, beOnDutyTime,offDutyTime,day) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      if(day==0){
        var t = new Date(beOnDutyTime);
        	var time =  this.format(t,'HH:mm:ss');
          time = util.fmtDates(new Date(d2*1000))+' '+time;
        var times = new Date(d2*1000);
        if(times.getHours()<t.getHours()){
          return "上班打卡";
        }else if (times.getHours()==t.getHours()){
          if(times.getMinutes()<=t.getMinutes()){
            return "上班打卡";
          }
          return "迟到";
        }else if(times.getHours()<18){
          return "迟到";
        }else{
          return "下班打卡";
        }
      }else{
        return "重复打卡";
      }

    },

    format(time, format) {
                    var t = new Date(time);
                    var tf = function (i) { return (i < 10 ? '0' : '') + i };
                    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
                        switch (a) {
                            case 'yyyy':
                                return tf(t.getFullYear());
                                break;
                            case 'MM':
                                return tf(t.getMonth() + 1);
                                break;
                            case 'mm':
                                return tf(t.getMinutes());
                                break;
                            case 'dd':
                                return tf(t.getDate());
                                break;
                            case 'HH':
                                return tf(t.getHours());
                                break;
                            case 'ss':
                                return tf(t.getSeconds());
                                break;
                        }
                    })
                },

    showAddDialogForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }
      this.editForm.id = 0
      this.editForm.name = "";
      this.editForm.serialNumber = "";
      this.editForm.startTime = "";
      this.editForm.endTime = "";
      this.editFormVisible = true;
    },
    handleEdit(index, row) {

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }
      this.editForm.id = row.id;
      this.editForm.name = row.name;
      this.editForm.serialNumber = row.serialNumber;
      this.editForm.startTime = row.startTime;
      this.editForm.endTime = row.endTime;
      this.editFormVisible = true;

    },
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {
          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = updateGoTimeFrame
          if(this.editForm.id == 0){
            func = addGoTimeFrame
          }
          func(this.editForm).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.name+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteGoTimeFrame({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getStaffLogsList({
        pageSize: this.pageSize,
        pageNum: pageNum,
        state: 200,
        name: this.searchForm.name,
        department: this.searchForm.department,
        position: this.searchForm.position,
        selectTime: this.searchForm.selectTime,
        selectTimeId: this.searchForm.selectTimeId,
        punchResult: this.searchForm.punchResult,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

      getDepartmentList().then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          this.department = res.data;
          // let expandRowKeys = [];
          // for(let i in this.tableData){
          //   expandRowKeys.push(''+this.tableData[i].id);
          // }
          // this.expandRowKeys = expandRowKeys;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

      getGoPositionList({
        pageSize: this.pageSize,
        pageNum: pageNum,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          // this.currentPage = pageNum;
          // this.total = data.total;
          this.position = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    clear(){
      this.searchForm.name = "";
      this.searchForm.department = "";
      this.searchForm.position = "";
      this.searchForm.selectTimeId = "";
      this.searchForm.selectTime = "";
      this.searchForm.punchResult = "";
    },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
  .element.style {
      overflow: scroll;
      height: 100vh;
  }
  .test-item-table{
    width: 100%;
    border-collapse: collapse;
    tr{
      height: 40px;
    }

    th, td {
      width: 7%;
      text-align: center;
      overflow: scroll;
      height: 100vh;
      border: 1px solid #CCC;
    }
    th {
      background-color: #EDF2FC;
    }
  }
  .chose-role{
    display: inline-block;
    margin-left: 20px;
    margin-bottom: 20px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
